package yb.ecp.fast.user.web;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.infra.util.StringUtil;
import yb.ecp.fast.user.infra.AuthCode;
import yb.ecp.fast.user.infra.BasicController;
import yb.ecp.fast.user.infra.ErrorCode;
import yb.ecp.fast.user.service.MenuService;
import yb.ecp.fast.user.service.ProfileService;
import yb.ecp.fast.user.service.RoleService;
import yb.ecp.fast.user.service.ScepterService;
import yb.ecp.fast.user.service.UserContextService;
import yb.ecp.fast.user.service.VO.MenusAuthsVO;
import yb.ecp.fast.user.service.VO.RoleMenuVO;
import yb.ecp.fast.user.service.VO.RoleUserVO;
import yb.ecp.fast.user.service.VO.RoleVO;
import yb.ecp.fast.user.service.VO.UserRoleRelationVO;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by john on 2017/10/31.
 */
@RestController
@RequestMapping(value = "/scepter")
public class ScepterController extends BasicController
{
    @Autowired
    ScepterService scepterService;

    @Autowired
    MenuService menuService;

    @Autowired
    UserContextService userContextService;

    @Autowired
    RoleService roleService;

    @Autowired
    ProfileService profileService;

    /**
     * 增加角色
     *
     * @param roleVO
     * @return
     */
    @RequestMapping(value = "role", method = RequestMethod.POST)
    @ApiOperation(value = "增加角色")
    @FastMappingInfo(needLogin = true, code = AuthCode.Role.ADD)
    public ActionResult role(@RequestBody RoleVO roleVO, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        Ref<String> roleIdRef = new Ref<>("");
        ErrorCode ret = scepterService.addRole(roleVO, roleIdRef, userId);
        return actionResult(ret, roleIdRef.get());
    }

    @RequestMapping(value = "deleteRole", method = RequestMethod.POST)
    @ApiOperation(value = "删除角色")
    @FastMappingInfo(needLogin = true,code = AuthCode.Role.DELETE)
    public ActionResult removeRole(@RequestParam("roleId")String roleId)
    {
        ErrorCode ret = scepterService.deleteRole(roleId);
        return actionResult(ret);
    }

    @RequestMapping(value = "deleteRoles", method = RequestMethod.POST)
    @ApiOperation(value = "批量删除角色")
//    @FastMappingInfo(needLogin = true,code = AuthCode.Role.BATCH_DELETE)
    public ActionResult removeRoles(@RequestBody List<String> roleIds)
    {
        List<String> usedRoles = scepterService.checkRolesUsed(roleIds);
        if (!ListUtil.isNullOrEmpty(usedRoles))
        {
            return actionResult(ErrorCode.RoleIsUsed, usedRoles);
        }
        usedRoles = scepterService.deleteRoles(roleIds);

        if (!ListUtil.isNullOrEmpty(usedRoles))
        {
            return actionResult(ErrorCode.FailedToRemoveRecord, usedRoles);
        }
        return actionResult(ErrorCode.Success);
    }

    @RequestMapping(value = "editRole", method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色")
    @FastMappingInfo(needLogin = true, code = AuthCode.Role.UPDATE)
    public ActionResult editRole(@RequestBody RoleVO roleVO, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        ErrorCode ret = scepterService.editRole(roleVO, userId);
        return actionResult(ret);
    }

    /*
    * 根据角色标识查询角色信息
     */
    @RequestMapping(value = "role", method = RequestMethod.GET)
    @ApiOperation(value = "根据角色标识查询角色信息", response = RoleVO.class)
    @FastMappingInfo(needLogin = true)
    public ActionResult role(@RequestParam("roleId")String roleId)
    {
        RoleVO ret = scepterService.getRole(roleId);
        return actionResult(ret);
    }

    @RequestMapping(value = "roles", method = RequestMethod.GET)
    @ApiOperation(value = "查询当前用户所在工作空间的所有角色信息", response = RoleVO.class, responseContainer = "List")
    @FastMappingInfo(needLogin = true)
    public ActionResult roles(@RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        //获取工作空间ID
        Ref<String> spaceIdRef = new Ref<>("");
        ErrorCode queryCode = profileService.queryWorkspaceId(userId, spaceIdRef);

        if (ErrorCode.Success != queryCode) {
            return actionResult(queryCode);
        }
        String spaceId = spaceIdRef.get();
        return roles(0, null, spaceId);
    }

    private ActionResult roles(int channel, Integer type,String spaceId)
    {
        List<RoleVO> ret = scepterService.getAllRoles(channel, type,spaceId);
        return actionResult(ret);
    }

    @RequestMapping(value = "allRoles", method = RequestMethod.GET)
    @ApiOperation(value = "获取平台所有角色(机场签单项目使用)")
    @FastMappingInfo(needLogin = true)
    public ActionResult allRoles(){
        return actionResult(scepterService.getAllRoles(0, null,null));
    }

    @RequestMapping(value = "roleUsers", method = RequestMethod.POST)
    @ApiOperation(value = "设置一批拥有该角色身份的用户")
    @FastMappingInfo(needLogin = true)
    public ActionResult roleUsers(@RequestBody RoleUserVO roleUserVO)
    {
        ErrorCode code = scepterService.setRoleUser(roleUserVO.getRoleId(), roleUserVO.getUserIds());
        return actionResult(code);
    }

    @RequestMapping(value = "roleUser", method = RequestMethod.POST)
    @ApiOperation(value = "设置一个拥有该角色身份的用户")
    @FastMappingInfo(needLogin = true)
    public ActionResult roleUser(@RequestBody UserRoleRelationVO userRoleVO)
    {
        ErrorCode code = scepterService.setRoleUser(userRoleVO.getRoleId(), userRoleVO.getUserId(),0);
        return actionResult(code);
    }

    @RequestMapping(value = "/removeRoleUser", method = RequestMethod.POST)
    @ApiOperation(value = "删除一个拥有该角色身份的用户")
    @FastMappingInfo(needLogin = true)
    public ActionResult removeRoleUser(@RequestBody UserRoleRelationVO userRoleVO)
    {
        ErrorCode code = scepterService.removeRoleUser(userRoleVO.getRoleId(), userRoleVO.getUserId());
        return actionResult(code);
    }

    @RequestMapping(value = "roleUserIds", method = RequestMethod.GET)
    @ApiOperation(value = "按角色标识获取所有拥有该角色身份的用户")
    @FastMappingInfo(needLogin = true)
    public ActionResult roleUserIds(@RequestParam("roleId")String roleId) throws Exception
    {
        List<String> userIds = scepterService.getUserIdByRoleId(roleId);
        return actionResult(userIds);
    }

    /**
     * 获取用户拥有的所有角色的标识,channel默认0,type默认0
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "userRoleIds", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult userRoles(@RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        return actionResult(scepterService.getRoleIdsByUserId(userId));
    }

    /**
     * 获取用户拥有的所有角色的标识,channel默认0,type默认0
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "userRolesList", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult userRolesList(@RequestParam("userId")String userId)
    {
        return actionResult(scepterService.getRolesByUserId(userId));
    }

    /**
     * 新增菜单
     *
     * @param roleMenuVO
     * @return
     */
    @RequestMapping(value = "/addMenu", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.Role.ADD_MENUS_BY_ROLE)
    public ActionResult addMenu(@RequestBody RoleMenuVO roleMenuVO)
    {
        ErrorCode code = scepterService.addMenu(roleMenuVO);
        return actionResult(code);
    }

    /**
     * 新增菜单和权限
     *
     * @param roleMenuVO
     * @return
     */
    @RequestMapping(value = "/addMenusAuths", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.Role.ADD_MENUS_AUTHS_BY_ROLE)
    public ActionResult addMenusAuths(@RequestBody RoleMenuVO roleMenuVO)
    {
        ErrorCode code = scepterService.addMenusAuths(roleMenuVO);
        return actionResult(code);
    }


    /**
     * 获取角色所属菜单ID集合
     *
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/getMenu", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult getMenu(@RequestHeader(name = "x-user-id", required = false) String userId, @RequestParam("roleId") String roleId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        List<Integer> menus = scepterService.listMenuIdByRoleId(roleId, userId);
        return actionResult(menus);
    }

    /**
     * 根据ID获取菜单和权限集合
     *
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/getMenusAuths", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult getMenusAuths(@RequestHeader(name = "x-user-id", required = false) String userId, @RequestParam("roleId") String roleId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        MenusAuthsVO menusAuthsVO = scepterService.listMenuAuthByRoleId(roleId, userId);
        return actionResult(menusAuthsVO);
    }

    /**
     * 获取用户所有的权限code
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getAuthCodes", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult<List<Integer>> getAuthCodes(@RequestParam(value = "userId", required = false) String userId, @RequestHeader(name = "x-user-id", required = false) String selfUserId) {
        if (StringUtil.isNullOrSpace(userId)) {
            return actionResult(scepterService.authCodesByUserId(selfUserId));
        } else {
            return actionResult(scepterService.authCodesByUserId(userId));
        }
    }

    @RequestMapping(value = "/queryRolesByDept", method = RequestMethod.GET)
    @ApiOperation("查询部门下角色集合")
    @FastMappingInfo(needLogin = true)
    public ActionResult queryRolesByDepartment(@RequestParam("deptId") String deptId, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        Ref<List> rolesRef = new Ref<>(new ArrayList());
        return actionResult(scepterService.queryRolesByDepartment(deptId, userId, rolesRef), rolesRef.get());
    }
}
